<template>
  <a-modal
    title="包材出库详情"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :footer="null"
    @ok="handleSubmit"
    @cancel="handleCancel">
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">

            <a-col :md="8" :sm="24" v-if="false">
              <a-form-item label="订单ID">
                <a-input v-model="queryParam.orderId" placeholder="请输入订单ID"/>
              </a-form-item>
            </a-col>

          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        :columns="dynamicColumn"
        :data="loadData"
        :alert="true"
        :showPagination="false">

        <template slot="normalNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.normalNumber" :step="1" :min="0" style="width: 67px;"/>
        </template>
        <template slot="extraNumber" slot-scope="text, record">
          <a-input-number v-model:value="record.extraNumber" :step="1" :min="0" style="width: 67px;"/>
        </template>
        <span slot="action" slot-scope="text, record">
          <a @click="$refs.outDetail.show(record)">出库记录</a>
        </span>
      </s-table>

    </a-card>

    <out-detail ref="outDetail"/>
  </a-modal>
</template>

<script>
import {STable} from '@/components'
import {page, del, add, listResult} from '@/api/modular/main/emsordermaterial/emsOrderMaterialManage'
import {addOutOrderForProductionOrder} from '@/api/modular/main/emsorder/emsOrderManage'
import addForm from '@/views/main/emsordermaterial/emsOrderMaterialAddFormOutOrder'
import editForm from '@/views/main/emsordermaterial/emsOrderMaterialEditForm'
import outDetail from './outDetail'
import materialForm from '@/views/main/emsmaterial/emsMaterialIndex'
import emsMaterialIndex1 from '@/views/main/emsmaterial/emsMaterialIndex1'
import productAddForm from '@/views/main/emsorder/emsOrderProductAddForm'
import productEditForm from '@/views/main/emsorder/emsOrderProductEditForm'

export default {
  components: {
    STable,
    addForm,
    editForm,
    materialForm,
    emsMaterialIndex1,
    productAddForm,
    productEditForm,
    outDetail,
  },
  props: {
    readonly: false,
  },
  data() {
    return {
      title: null,
      advanced: false, // 高级搜索 展开/关闭
      queryParam: {},  // 查询参数
      viewState: '',
      viewStateEnum: {
        materialOut: 'materialOut',
        cableOut: 'cableOut',
        packingOut: 'packingOut',
        packingOutReadonly: 'packingOutReadonly',
      },
      extra: {},
      columnsByProductionOrderPackingOutStore: [
        {
          title: '序号', width:'80px',
          dataIndex: '',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '包材编号',
          dataIndex: 'materialCode'
        },
        {
          title: '包材名称',
          dataIndex: 'materialName',
        },
        {
          title: '已出库数量',
          dataIndex: 'completedNumber'
        },
        {
          title: '单价',
          dataIndex: 'costPrice',
        },
        {
          title: '成本',
          dataIndex: 'normalNumber',
          customRender: (text, record, index) => `${record.costPrice * record.completedNumber}`
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: {customRender: 'action'}
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return page(Object.assign(parameter, this.queryParam)).then((res) => {
          res.data.rows.forEach(value => {
            value.normalNumber = 0
          })
          return res.data
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      defaultExpandedKeys: [],
      replaceFields: {
        key: 'id',
      },
      visible: false,
      confirmLoading: false,
      emsOrder: null,
    }
  },
  computed: {
    dynamicColumn() {
        return this.columnsByProductionOrderPackingOutStore
    },
  },
  methods: {
    show(record, title, viewState, extra) {
      this.visible = true
      this.emsOrder = record
      this.title = title
      this.viewState = viewState
      this.extra = extra

      this.queryParam.orderId = record.orderId
      this.queryParam.pageSize = -1
      this.queryParam.materialType = this.$businessEnum.MATERIAL_TYPE_ENUM.packing.id

      setTimeout(() => {
        this.handleOk()
      }, 100)
    },
    del(record) {
      del(record).then((res) => {
        if (res.success) {
          this.$message.success('删除成功')
          this.$refs.table.refresh()
        } else {
          this.$message.error('删除失败：' + res.message)
        }
      }).catch((err) => {
        this.$message.error('删除错误：' + err.message)
      })
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleSubmit() {
      let emsOrder = this.emsOrder
      let $data = this.$refs.table.$data
      $data = $data.localDataSource

      let orderMaterials = $data.map(value => {
        return Object.assign({}, value, {
          sourceOrderId: emsOrder.orderId,
          sourceOrderMaterialId: value.orderMaterialId,
          number: value.normalNumber,
          extraNumber: value.extraNumber,
        })
      })

      let orderBean = {
        orderId: '',
        sourceOrderId: emsOrder.orderId,
        orderParentId: '',
        orderPids: '',
        orderNumber: '',
        orderType: this.$businessEnum.ORDER_TYPE_ENUM.outOrder.id,
        orgId: '',
        targetOrgId: '',
        isOverseasStore: '',
        countryCode: '',
        file: '',
        remark: '',
        executeStatus: '',
        executeProgress: '',
        issueTime: '',
        estimateCompletionTime: '',
        receiveTime: '',
        status: '',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
        orderMaterials: orderMaterials,
      }
      addOutOrderForProductionOrder(orderBean).then(res => {
        console.log(`生产单出库响应结果:${res.data}`)
        if (res.success) {
          this.$message.info('出库成功')
          this.handleOk()
        } else {
          this.$message.error('出库失败：' + res.message)
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    onEmsMaterialIndex1Selected(materialRow) {
      // console.log(`选择了原料:id=${materialRow.materialId}, code=${materialRow.materialCode}, name=${materialRow.materialName}`)
      let {materialId, materialName, materialCode, materialType, costPrice} = materialRow
      // 需要调用接口往订单中添加物料
      let _emsOrder = Object.assign({}, this.emsOrder)
      _emsOrder.orderMaterials = []
      let orderMaterial = {
        orderMaterialId: '',
        orderId: _emsOrder.orderId,
        bomId: '0',  // 单独选择原料时没有BOMID
        materialId: materialId,
        number: 1,
        completedNumber: 0,
        executeStatus: '0',
        executeProgress: '0',
        status: '0',
        createTime: '',
        createUser: '',
        updateTime: '',
        updateUser: '',
      }
      _emsOrder.orderMaterials.push(orderMaterial)
      add(orderMaterial).then(res => {
        if (res.success) {
          this.$message.success('新增成功')
          // this.handleCancel()
          // this.$emit('ok', values)
          this.$refs.table.refresh()
        } else {
          this.$message.info('新增失败：' + res.message)
        }
      })
      // 然后刷新table控件
    }
  }
}
</script>

<style lang="less">
.table-operator {
  margin-bottom: 18px;
}

button {
  margin-right: 8px;
}
</style>
